#include "NewtonInterpolation.h"
#include <matplotlibcpp.h>
#include <cmath>
#include <vector>
using namespace std;
class GivenFunction {
public:
    double operator()(double x) const {
        return 1.0 / (1.0 + 25 * x * x);
    }
};

vector<double> chebyshevNodes(int n) {
    vector<double> nodes;
    for (int k = 0; k < n; ++k) {
        nodes.push_back(cos((2 * k + 1) * acos(-1) / (2 * n)));
    }
    return nodes;
}

int main() {
    vector<int> ns = {5, 10, 15, 20}; // n值
    double x_min = -1, x_max = 1, step = 0.01;
    vector<double> x_fine;
    for (double x = x_min; x <= x_max; x += step) {
        x_fine.push_back(x);
    }
    vector<double> y_true, y_interpolated;

    for (int n : ns) {
        vector<double> nodes = chebyshevNodes(n);
        vector<double> func_values;
        for (double x : nodes) {
            func_values.push_back(GivenFunction()(x));
        }

        y_interpolated.clear();
        for (double x : x_fine) {
            y_interpolated.push_back(newtonInterpolation(nodes, func_values, x));
        }

        // 绘制精确函数和插值多项式
        vector<double> y_true;
        for (double x : x_fine) {
            y_true.push_back(GivenFunction()(x));
        }
        
        matplotlibcpp::figure();
        matplotlibcpp::named_plot("True Function", x_fine, y_true, "b");
        matplotlibcpp::named_plot("Interpolated Polynomial " + to_string(n), x_fine, y_interpolated, "r--");
        matplotlibcpp::legend();
        matplotlibcpp::show();
    }

    return 0;
}